/*
 * This file is part of the <a href="http://code.google.com/p/pux">PUX Framework</a>
 *
 * Copyright 2008 by <a href="mailto:jfendler@polytechnic.edu.na">Jens Fendler</a>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package de.teamskill.pux.library.image;

import java.awt.image.BufferedImage;

import de.teamskill.pux.engine.InputPort;

/**
 * ColorToGrayImageNode - convert the BufferedImage on the input port into the
 * corresponding grayscale image on the output port
 * 
 * @author <a href="mailto:jfendler@polytechnic.edu.na">Jens Fendler</a>
 * 
 */
public class ColorToGrayImageNode extends AbstractImageFilter {

	/**
	 * imageType
	 */
	private InputPort imageType;

	/**
	 * ColorToGrayImageNode Constructor
	 * 
	 */
	public ColorToGrayImageNode() {
		this("COLOR2GRAY" + nr++, false);
	}

	/**
	 * ColorToGrayImageNode Constructor
	 * 
	 * @param name
	 * @param continuous
	 */
	public ColorToGrayImageNode(String name, boolean continuous) {
		super(name, continuous);
	}

	/**
	 * @see de.teamskill.pux.engine.AbstractNode#compute()
	 */
	public void compute() {
		BufferedImage ci = (BufferedImage) in.fetchData();
		BufferedImage gi = new BufferedImage(ci.getWidth(), ci.getHeight(), (Integer) imageType.fetchData());
		LOG_NODE.fine("Copying image data for " + ci.getWidth() + "x" + ci.getHeight() + " pixels.");
		for (int x = 0; x < ci.getWidth(); x++) {
			for (int y = 0; y < ci.getHeight(); y++) {
				int packed = ci.getRGB(x, y);
				int red = (packed & 0xff0000) >> 16;
				int green = (packed & 0x00ff00) >> 8;
				int blue = (packed & 0x0000ff);
				gi.setRGB(x, y, (red + green + blue) / 3);
			}
		}
		out.pushData(gi);
	}

	/**
	 * @see de.teamskill.pux.library.image.AbstractImageFilter#createPorts()
	 */
	protected void createPorts() {
		super.createPorts();
		imageType = addConfigurationPort("imageType", Integer.class,
				new Integer(BufferedImage.TYPE_BYTE_GRAY));
	}

}
